/*
 * @Author: your name
 * @Date: 2021-04-02 13:11:49
 * @LastEditTime: 2021-04-06 13:37:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \my-app-koa\routes\api\posts.js
 */

const Router = require("koa-router")
const router = new Router()

const passport = require('koa-passport')
// 引入Profile 模型
const Post = require("../../models/Post")
// 引入Profile
const Profile = require("../../models/Profile")

// 引入验证
const validatePostInput = require("../../validation/post")

/**
 * @route GET api/posts/test
 * @desc 测试接口地址
 * @access 接口公开的
 */

router.get('/test', async ctx => {
  ctx.status = 200
  ctx.body = {
    msg: 'posts is ok'
  }
})

/**
 * @route POST api/posts/
 * @desc 新增评论
 * @access 接口公开的
 */

router.post('/', passport.authenticate('jwt', { session: false }), async ctx => {

  const { errors, isValid } = validatePostInput(ctx.request.body)
  if (!isValid) {
    ctx.status = 400
    ctx.body = errors
    return
  }
  const user_id = ctx.state.user.id
  const { text, name, avatar } = ctx.request.body
  const newPost = new Post({
    user: user_id,
    text, name, avatar
  })

  await newPost.save().then(post => ctx.body = post).catch(err => ctx.body = err);
  ctx.status = 200
  ctx.body = newPost

})

/**
 * @route GET api/posts/all
 * @desc 获取所有留言
 * @access 接口公开的
 */

router.get('/', async ctx => {
  await Post.find()
    .sort({ date: -1 })
    .then(posts => {
      ctx.status = 200
      ctx.body = posts
    }).catch(err => {
      ctx.status = 400
      ctx.body = {
        msg: '找不到任何留言信息'
      }
    })

})


/**
 * @route GET api/posts?id=xx
 * @desc 获取id对应的留言
 * @access 接口公开的
 */

router.get('/:id', async ctx => {
  const id = ctx.params.id;
  if (!id) {
    ctx.status = 200;
    ctx.body = {
      msg: '非法访问'
    }
    return
  }
  await Post.findById(id)
    .then(post => {
      ctx.status = 200
      ctx.body = post
    }).catch(err => {
      ctx.status = 400
      ctx.body = {
        msg: '找不到任何留言信息'
      }
    })

})

/**
 * @route DELETE api/posts/
 * @desc 删除单个评论
 * @access 接口公开的
 */

router.delete('/:id', passport.authenticate('jwt', { session: false }), async ctx => {

  const id = ctx.params.id;
  if (!id) {
    ctx.status = 200;
    ctx.body = {
      msg: '非法访问'
    }
    return
  }
  const user_id = ctx.state.user.id
  // 查看用户是否存在个人信息
  const profile = await Profile.find({ user: id })
  const post = await Post.findById(id)
  if (!profile || !post) {
    ctx.status = 200;
    ctx.body = {
      msg: '没有个人信息'
    }
    return
  }
  if (post.user.toString() !== user_id) {
    ctx.status = 200;
    ctx.body = {
      msg: '无权限删除改评论'
    }
    return
  }
  await Post.remove({ _id: id })
    .then(() => {
      ctx.status = 200;
      ctx.body = { success: true }
    })
    .catch(err => {
      ctx.status = 400;
      ctx.body = err
    })
  // 查看对应的留言
  // 判断是否是本人
  // 删除评论
  // 返回


})



/**
 * @route POST api/posts/like?id=xxx
 * @desc 点赞接口
 * @access 接口公开的
 */

router.post('/like/:id', passport.authenticate('jwt', { session: false }), async ctx => {

  const id = ctx.params.id
  if (!id) {
    ctx.status = 404
    ctx.body = {
      msg: '非法访问'
    }
    return
  }
  const user_id = ctx.state.user.id
  // 查询用户信息
  const profile = await Profile.find({ user: user_id });
  if (profile) {
    // 查询留言
    const post = await Post.findById(id)
    const isLike = post.likes.filter(like => like.user.toString() === user_id).length > 0
    if (isLike) {
      ctx.status = 400;
      ctx.body = {
        msg: '该用户已点过赞'
      }
      return
    }
    // 添加点赞
    post.likes.unshift({ user: user_id })
    // 更新留言信息
    const postUpdate = await Post.findOneAndUpdate({ _id: id }, { $set: post }, { new: true })
    ctx.status = 200
    ctx.body = postUpdate
  } else {
    ctx.status = 404
    ctx.body = {
      msg: 'profile不存在'
    }
  }
})


/**
 * @route POST api/posts/unlike?id=xxx
 * @desc 取消点赞接口
 * @access 接口公开的
 */

router.post('/unlike/:id', passport.authenticate('jwt', { session: false }), async ctx => {

  const id = ctx.params.id
  if (!id) {
    ctx.status = 404
    ctx.body = {
      msg: '非法访问'
    }
    return
  }
  const user_id = ctx.state.user.id
  // 查询用户信息
  const profile = await Profile.find({ user: user_id });
  if (profile) {
    // 查询留言
    const post = await Post.findById(id)
    const isLike = post.likes.filter(like => like.user.toString() === user_id).length === 0
    if (isLike) {
      ctx.status = 400;
      ctx.body = {
        msg: '该用户没有点赞过'
      }
      return
    }
    const removeIndex = post.likes.map(item => item.user.toString()).indexOf(user_id)
    // 添加点赞
    post.likes.splice(removeIndex, 1)
    // 更新留言信息
    const postUpdate = await Post.findOneAndUpdate({ _id: id }, { $set: post }, { new: true })
    ctx.status = 200
    ctx.body = postUpdate
  } else {
    ctx.status = 404
    ctx.body = {
      msg: 'profile不存在'
    }
  }
})


/**
 * @route POST api/posts/comment?id=xxx
 * @desc 添加评论接口
 * @access 接口公开的
 */

router.post('/comment/:id', passport.authenticate('jwt', { session: false }), async ctx => {

  const id = ctx.params.id
  if (!id) {
    ctx.status = 404
    ctx.body = {
      msg: '非法访问'
    }
    return
  }
  const user_id = ctx.state.user.id
  const { text } = ctx.request.body;
  let newComment = {
    user: user_id,
    text
  }
  // 查询用户信息
  const profile = await Profile.find({ user: user_id });
  if (profile) {
    // 查询评论
    const post = await Post.findById(id)
    post.comments.unshift(newComment)
    // 更新评论信息
    const postUpdate = await Post.findOneAndUpdate({ _id: id }, { $set: post }, { new: true })
    ctx.status = 200
    ctx.body = postUpdate
  } else {
    ctx.status = 404
    ctx.body = {
      msg: 'profile不存在'
    }
  }
})

/**
 * @route DELETE api/posts/comment?id=xxx&comment_id
 * @desc 添加评论接口
 * @access 接口公开的
 */

router.delete('/comment/:id', passport.authenticate('jwt', { session: false }), async ctx => {

  const { id, comment_id } = ctx.query
  if (!id || !comment_id) {
    ctx.status = 404
    ctx.body = {
      msg: '非法访问'
    }
    return
  }
  const user_id = ctx.state.user.id
  // 查询用户信息
  const profile = await Profile.find({ user: user_id });
  if (profile) {
    // 查询评论
    const post = await Post.findById(id)
    const removeIndex = post.comments.findIndex(comment => comment._id.toString() === comment_id)
    if (removeIndex === -1) {
      ctx.status = 400
      ctx.body = {
        msg: '评论不存在'
      }
      return
    }
    post.comments.splice(removeIndex, 1)
    // 更新评论信息
    const postUpdate = await Post.findOneAndUpdate({ _id: id }, { $set: post }, { new: true })
    ctx.status = 200
    ctx.body = postUpdate
  } else {
    ctx.status = 404
    ctx.body = {
      msg: 'profile不存在'
    }
  }
})


module.exports = router.routes();
